package com.hxkcloud.patient.aerotel.task;

import android.content.Context;
import android.graphics.Bitmap;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;


import com.hxkcloud.patient.aerotel.domain.health.AerotelECGPdu;
import com.hxkcloud.patient.aerotel.isUpLoadDataListener;
import com.hxkcloud.patient.aerotel.util.F;
import com.hxkcloud.patient.aerotel.util.Picture;
import com.hxkcloud.patient.beans.LoginInfo;
import com.hxkcloud.patient.dborm.LoginInfoDao;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by daipengfei on 16/3/28.
 */
public class UploadTask extends AsyncTask<Long, Integer, JSONObject> {
    public static final String url = "http://47.94.172.81:8080/nightingale/cardiographReport.app/takeReportList";

    private static final String TAG = UploadTask.class.getSimpleName();
    private AerotelECGPdu pdu;
    private static boolean flag = false;
    private Context context;
    private String bluetoothId;
    private isUpLoadDataListener loadLisneter;
    private LoginInfo user;


    public UploadTask(Context context, AerotelECGPdu p) {
        this.context = context;
        this.pdu = p;
    }

    @Override
    protected JSONObject doInBackground(Long... params) {
        File dir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        String xmlfile = dir.getAbsolutePath() + File.separator + pdu.file + ".xml";
        File xml = new File(xmlfile);
        String imgfile = dir.getAbsolutePath() + File.separator + pdu.file + ".jpg";
        Log.e("deviceSN===========>", pdu.devicesn);
        Picture picture = new Picture(imgfile, true);
        Bitmap param = F.getBitmapByParam(picture);//获取图片
        F.comPressBitmapByParam(picture, param);//压缩图片
        File img = new File(picture.getZoomPath());//压缩路径
        LoginInfoDao userDao = new LoginInfoDao(context);
        user = userDao.getUser();
        String id = user.getUserId();
        String bluetoothID = pdu.header.getBluetoothID();

        try {
            bluetoothId = URLEncoder.encode(bluetoothID, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Log.e("bluetoothId", bluetoothId);
//        String filename = pdu.header.getBluetoothID() + "_" + pdu.createdDate.replaceAll(":| |-", "");
        String filename = bluetoothId + "_" + pdu.createdDate.replaceAll(":| |-", "");
        Log.e(TAG, " pdu.header.getBluetoothID()" + pdu.header.getBluetoothID());
        Log.e(TAG, " pdu.createdDate" + pdu.createdDate);
        Log.e(TAG, "filename" + filename);
        RequestBody xmlbody = RequestBody.create(MediaType.parse("application/octet-stream"), xml);
        RequestBody imgbody = RequestBody.create(MediaType.parse("application/octet-stream"), img);
        //上传心电
        uploadHdc(context, id, bluetoothId, pdu.createdDate, filename, xmlbody, imgbody);
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    public void setLoadDataComplete(isUpLoadDataListener dataComplete) {
        this.loadLisneter = dataComplete;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);
        if (loadLisneter != null) {
            loadLisneter.loadComplete();
        }
    }

    /**
     * 上传心电
     *
     * @return
     */
    public static void uploadHdc(final Context context, String patientId, String bluetoothId, String checkTime, String filename, RequestBody xmlbody, RequestBody imgbody) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        String u = url + "/uploadhdc2";
//		if(patientId==null){
//			BaseToast.showToast(context, "patientId不能为空");
//			return;
//		}
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("patientId", patientId).addFormDataPart("btmac", bluetoothId)
                .addFormDataPart("checkTime", checkTime)
                .addPart(Headers.of(
                        "Content-Disposition",
                        "form-data; name=\"ecgraw\";filename=\"" + filename + ".xml\""), xmlbody)
                .addPart(Headers.of(
                        "Content-Disposition",
                        "form-data; name=\"ecgraph\";filename=\"" + filename + ".jpg\""), imgbody)
                .build();


//        long timeMillis = GlobalService.getCurrentTime(context);
//        int randomNumber = 100000 + (int) (900000 * Math.random());
//        String md5 = DigestUtils.md5Hex(RequestValidatorConstants.ANDROID_HDC_KEY + timeMillis * randomNumber);
        Request request = new Request.Builder()
                .url(u)
//                .header(RequestValidatorConstants.HEADER_CHANNEL_TYPE,
//                        "h:p")
//                .header(RequestValidatorConstants.HEADER_VALID,
//                        timeMillis + ":" + randomNumber + ":" + md5)
                .post(requestBody)
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e("请求错误", "===========》");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    //成功
                    flag = true;
                    String res = response.body().string();
//                    Log.e("res",res);
//                    if (handler == null || TextUtils.isEmpty(res))
//                        return;
//                    Message msg = new Message();
//                    Bundle data = new Bundle();
//                    data.putString(,
//                            res);
//                    msg.setData(data);
//                    handler.sendMessage(msg);
                }
            }
        });
    }
}